/*
 *所有关于SNTable类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*SNTableService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using MyMES.IRepositories;
using MyMes.Infrastructure;
using System.Threading.Tasks;
using VOL.Core.Utilities.Response;
using VOL.Entity.DomainModels.Core;
using MyMES.Dto;
using System;

namespace MyMES.Services
{
    public partial class SNTableService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBaseRepository<SNTable> _sNTableRepo;
        private readonly IBaseRepository<MaterialProduct> _materialProductRepo;
        private readonly ISNTableRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public SNTableService(
            ISNTableRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBaseRepository<SNTable> sNTableRepo,
            IBaseRepository<MaterialProduct> materialProductRepo
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _sNTableRepo = sNTableRepo;
            _materialProductRepo = materialProductRepo;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        
        /// <summary>
        /// 添加SN码
        /// </summary>
        /// <param name="sNTable">SN码实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> AddSNTable(SNTable sNTable)
        {
            var res = new WebResponseContent();
            
            var i = await _sNTableRepo.AddAsync(sNTable);
            
            res.OK("新增成功");
            
            return await Task.FromResult(res);
        }
        
        /// <summary>
        /// 获取SN码列表
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>分页后的SN码列表</returns>
        public async Task<PageGridData<SNTableDTO>> GetSNTable(GetSNTableDTO dto)
        {
            PageGridData<SNTableDTO> pageData = new PageGridData<SNTableDTO>();
            
            try
            {
                var sNTableList = (from a in _sNTableRepo.GetAll()
                                  join b in _materialProductRepo.GetAll() on a.MaterialCode equals b.MaterialCode into materialTemp
                                  from material in materialTemp.DefaultIfEmpty()
                                  select new SNTableDTO()
                                  {
                                      Id = a.Id,
                                      MaterialCode = a.MaterialCode,
                                      BatchNumber = a.BatchNumber,
                                      Quantity = a.Quantity,
                                      ProductionTime = a.ProductionTime,
                                      MaterialName =material.MaterialName,
                                      Specification = material.Specification,
                                      Flats=material.Flats
                                  });
                
                // 根据条件筛选数据
                sNTableList = sNTableList.WhereIF(!string.IsNullOrEmpty(dto.MaterialCode),
                                    x => x.MaterialCode.Contains(dto.MaterialCode));
                
                sNTableList = sNTableList.WhereIF(!string.IsNullOrEmpty(dto.MaterialName),
                                    x => x.MaterialName != null && x.MaterialName.Contains(dto.MaterialName));
                
                sNTableList = sNTableList.WhereIF(!string.IsNullOrEmpty(dto.BatchNumber),
                                    x => x.BatchNumber != null && x.BatchNumber.Contains(dto.BatchNumber));
                
                // 计算总记录数
                pageData.total = await sNTableList.CountAsync();
                
                // 分页并排序
                var data = await sNTableList.OrderByDescending(a => a.Id)
                                .Skip((dto.PageIndex - 1) * dto.PageSize)
                                .Take(dto.PageSize)
                                .ToListAsync();
                
                pageData.rows = data;
                pageData.status = 1;
            }
            catch (Exception ex)
            {
                pageData.status = 0;
                pageData.msg = $"获取SN码列表失败：{ex.Message}";
            }
            
            return pageData;
        }
        
        /// <summary>
        /// 删除SN码
        /// </summary>
        /// <param name="id">SN码ID，多个ID用逗号分隔</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> RemSNTable(string id)
        {
            var res = new WebResponseContent();
            
            var i = await _sNTableRepo.DelAll(x => id.Contains(x.Id.ToString()));
            
            res.OK("删除成功");
            
            return await Task.FromResult(res);
        }
    }
}
